// 页面加载完成后执行
$(document).ready(function() {
    // 初始化日期选择器
    initDateRangePicker();
    // 加载图表和数据
    loadCharts();
});

// 初始化日期选择器
function initDateRangePicker() {
    $('#daterange').daterangepicker({
        startDate: moment(startTime),
        endDate: moment(endTime),
        locale: {
            format: 'YYYY-MM-DD',
            applyLabel: '确定',
            cancelLabel: '取消',
            customRangeLabel: '自定义范围'
        }
    }, function(start, end) {
        window.location.href = '/admin/statistics?startTime=' + start.format('YYYY-MM-DD') + '&endTime=' + end.format('YYYY-MM-DD');
    });
}

// 加载所有图表
function loadCharts() {
    loadOrderTrend();
    loadItemDistribution();
    loadRankingTables();
}

// 加载订单趋势图
function loadOrderTrend() {
    $.get('/admin/statistics/order-trend', {
        startTime: startTime,
        endTime: endTime
    }, function(data) {
        const chart = echarts.init(document.getElementById('orderTrendChart'));
        const option = {
            title: {
                text: '订单趋势'
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    const date = params[0].name;
                    const count = params[0].value;
                    return `${date}<br/>订单数：${count}`;
                }
            },
            xAxis: {
                type: 'category',
                data: data.map(item => item.date),
                axisLabel: {
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '订单数'
            },
            series: [{
                data: data.map(item => item.count),
                type: 'line',
                smooth: true,
                areaStyle: {
                    opacity: 0.3
                },
                itemStyle: {
                    color: '#409EFF'
                }
            }]
        };
        chart.setOption(option);
    });
}

// 加载物品分布图
function loadItemDistribution() {
    $.get('/admin/statistics/item-distribution', {
        startTime: startTime,
        endTime: endTime
    }, function(data) {
        const chart = echarts.init(document.getElementById('itemDistributionChart'));
        const option = {
            title: {
                text: '物品分布'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [{
                type: 'pie',
                radius: '70%',
                data: data.map(item => ({
                    name: item.name,
                    value: item.count
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        chart.setOption(option);
    });
}

// 加载排名表格
function loadRankingTables() {
    // 加载回收员排名
    $.get('/admin/statistics/top-collectors', {
        startTime: startTime,
        endTime: endTime
    }, function(data) {
        const tbody = $('#collectorTable tbody');
        tbody.empty();
        data.forEach((item, index) => {
            tbody.append(`
                <tr>
                    <td>${index + 1}</td>
                    <td>${item.name}</td>
                    <td>${item.orderCount}</td>
                    <td>${item.rating.toFixed(1)}</td>
                </tr>
            `);
        });
    });

    // 加载回收站排名
    $.get('/admin/statistics/top-stations', {
        startTime: startTime,
        endTime: endTime
    }, function(data) {
        const tbody = $('#stationTable tbody');
        tbody.empty();
        data.forEach((item, index) => {
            tbody.append(`
                <tr>
                    <td>${index + 1}</td>
                    <td>${item.name}</td>
                    <td>${item.orderCount}</td>
                    <td>${item.weight.toFixed(2)}</td>
                </tr>
            `);
        });
    });

    // 加载区域排名
    $.get('/admin/statistics/top-areas', {
        startTime: startTime,
        endTime: endTime
    }, function(data) {
        const tbody = $('#areaTable tbody');
        tbody.empty();
        data.forEach((item, index) => {
            tbody.append(`
                <tr>
                    <td>${index + 1}</td>
                    <td>${item.name}</td>
                    <td>${item.orderCount}</td>
                    <td>${item.stationCount}</td>
                </tr>
            `);
        });
    });
}

// 导出报表
function exportReport() {
    window.location.href = `/admin/statistics/export?startTime=${startTime}&endTime=${endTime}`;
}

// 格式化数字
function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
}

// 格式化日期时间
function formatDateTime(datetime) {
    return moment(datetime).format('YYYY-MM-DD HH:mm:ss');
}

// 显示错误提示
function showError(message) {
    Swal.fire({
        icon: 'error',
        title: '错误',
        text: message
    });
}

// 显示成功提示
function showSuccess(message) {
    Swal.fire({
        icon: 'success',
        title: '成功',
        text: message,
        timer: 2000,
        showConfirmButton: false
    });
}

// 窗口大小改变时重新调整图表大小
window.addEventListener('resize', function() {
    const orderTrendChart = echarts.getInstanceByDom(document.getElementById('orderTrendChart'));
    const itemDistributionChart = echarts.getInstanceByDom(document.getElementById('itemDistributionChart'));
    if (orderTrendChart) {
        orderTrendChart.resize();
    }
    if (itemDistributionChart) {
        itemDistributionChart.resize();
    }
}); 